w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Remove files for a lot of directories - Linux
We're not going to enter sub directories so no need to use find; everything is at the same level. I think this is what you're looking for: rm */*.txt Before you run this you can try echo */*.txt to see if the correct files are going to be removed. Using find would be useful if you want to search subfolders of subfolders, etc. There is no Dir1 in the current folder so don't do find Dir1 .... If you run the find from the prompt above this will work: find . -type f -name "*.txt" -delete

Categories : Linux

How can I manage Linux settings (config) files in different directories in a single Git repo in another directory?
You can use symlinks. It is indeed what dotfiles managers such as homesick do. It is helpful to have a script to generate all the links automatically for you, in case you want to clone your setup to another box.

Categories : Linux

How do I enumerate through a directory in Objective-C, and essentially clear out all the directories of non-directory files?
Something like this will work: NSURL *rootURL = ... // File URL of the root directory you need NSFileManager *fm = [NSFileManager defaultManager]; NSDirectoryEnumerator *dirEnumerator = [fm enumeratorAtURL:rootURL includingPropertiesForKeys:@[NSURLNameKey, NSURLIsDirectoryKey] options:NSDirectoryEnumerationSkipsHiddenFiles errorHandler:nil]; for (NSURL *url in dirEnumerator) { NSNumber *isDirectory; [url getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:NULL]; if (![isDirectory boolValue]) { // This is a file - remove it [fm removeItemAtURL:url error:NULL]; } }

Categories : Objective C

Copy files from source directory to target directory and exclude specific file types from specified directories
This is one way to do it $SourceDirectory = 'C:Source' $DestinationDirectory = 'C:Destination' $ExcludeExtentions = '*.txt*', '*.xml*' $ExcludeSubDirectory = 'C:Sourcead_directory1', 'C:Sourcead_directory2' Get-ChildItem $SourceDirectory -Recurse -Exclude $ExcludeExtentions | Where-Object { $ExcludeSubDirectory -notcontains $_.DirectoryName } | Copy-Item -Destination $DestinationDirectory Your best friend here is Where-Object, or where. It takes a scriptblock as parameter and uses that scriptblock to validate each object that goes through pipeline. Only objects that make script return $true are passed through Where-Object. Also, take a look at the object that represents a file you get from Get-ChildItem. It has Name, Directory and DirectoryName containing pieces of file's FullNam

Categories : File

Linux zip a directory excluding some internal directories
It's not an error, it's a warning. Archives containing absolute paths to files are a security risk. Imagine an archive containing /etc/passwd. If you insist upon having the absolute paths in the archive, use the -P option: -P, --absolute-names don't strip leading `/'s from file names

Categories : Linux

What do I do to make a python script that can run from any directory: the script file doesn’t have to be in the same directory as the .csv files?
Assuming you mean to include a fixed CSV file with your code, store an absolute path based on the script path: HERE = os.path.dirname(os.path.abspath(__file__)) csv_filename = open(os.path.join(HERE, 'somefile.csv') __file__ is the filename of the current module or script, os.path.dirname(__file__) is the directory the module resides in. For scripts, __file__ can be a relative pathname, so we use os.path.abspath() to turn that into an absolute path. This means you can run your script from anywhere. If you meant to make your script work with arbitrary CSV input files, use command line options: import argparse if __name__ == '__main__': parser = argparse.ArgumentParser('CSV importer') parser.add_argument('csvfile', type=argparse.FileType('w'), default

Categories : Python

Copy a single file to all sub directories under a certain directory using Ant Script
The following example uses the groovy ANT task. Example ├── build.xml ├── lib │   └── groovy-all-2.1.6.jar ├── src │   └── index.html └── target └── DirectoryA ├── index.html ├── SubdirectoryAA │   └── index.html └── SubdirectoryAB ├── index.html └── SubdirectoryABA └── index.html build.xml <project name="demo" default="copy"> <path id="build.path"> <pathelement location="lib/groovy-all-2.1.6.jar"/> </path> <target name="copy"> <taskdef name="groovy" classname="org.codehaus.groovy.ant.Groovy" classpathref="build.path"/> <dirset id="trgDirs" dir="ta

Categories : PHP

How can I list files and directories with them directory levels
I think you can use file path as key and level number as value using dictionary. and parse the file path string to calculate level number, use string.split string[] words = s.Split('\');

Categories : C#

Running a script in nested directories without repercussions in the executing directory
in your first script change: ./gdp $file; to ./gdp $file $dirname; in your second script change: ' $1 > summary_$1; sort -k2n summary_$1 | uniq > holder; cat temp > useragents_$1; cat holder >> useragents_$1; more useragents_$1; to ' $1 > $2/summary_$1; sort -k2n $2/summary_$1 | uniq > $2/holder; cat temp > $2/useragents_$1; cat $2/holder >> $2/useragents_$1; more $2/useragents_$1;

Categories : Linux

Replace multiple files in sub directories with file from a different directory
try this: cd /d "C:Users----DocumentsTrainRuns" FOR /D /R %%a IN (*) do if exist "%%~a est1.hfl" echo copy /y "test1.hfl" "%%~a" Look at the output and remove the word echo if it looks good. Accepting an answer - how does it work?

Categories : Windows

Batch Command to Move Files from Sub Directories to New Directory
Try using For /F "TOKENS=1 DELIMS=%_TabSpace%" %%B In ('dir %1 /a-d /S /B /OD') DO ( the /s will cause recursion. The downside is that the output of the dir command is then d:pathfile.ext - which may not marry well with your "TOKENS=1 DELIMS=%_TabSpace%". You'd probably need to use "delims=" (ie, no delimiters, hence entire line in token1). You can then retrieve the various parts of the full-filename as %%~dB, %%~pB, %%~nB and %%~xB (the drive, path, naem and extension - and you can combine these parts if you wish by using %%~nxB for name+extension, for instance. Supplemental info - batch commented. @ECHO OFF SETLOCAL :: The above two lines are a traditional batch introduction. :: The first turns `ECHO`ing of the command to the console OFF :: The second makes all changes to the en

Categories : Windows

How to output CSS files to single directory from several input directories?
Consider creating a sass directory with dummy files for each of your components: project/ css/ foo.css bar.css baz.css modules/ foo/ foo.scss bar/ bar.scss baz/ baz.scss sass/ foo.scss bar.scss baz.scss Each dummy file should import the corresponding component. sass/foo.scss: @import "../modules/foo/foo.scss"; When you have all dummy files set up, run sass --update sass:css from the root of your project.

Categories : CSS

I'm trying to compress some files from one directory to another but I'm getting access denied on one of the directories why?
It doesn't work because you pass a directory name for the second parameter to CompressDirectory. You should pass a file name like.... string output = Path.Combine(zippedFileDirectory, "MyZipFile.7z"); ..... compressor.CompressDirectory(source, output);

Categories : C#

Shell script cannot be executed from some directories even though its directory is added to the "PATH" variable
You should add the complete path to your bin directory, not just bin. If bin is in your $HOME, you can add $HOME/bin or ~/bin.

Categories : Linux

searching for values stored in an arraylist through all the files within a directory and its sub directories
List all the files in a directory. `public void listFilesAndFilesSubDirectories(String directoryName){ File directory = new File(directoryName); //get all the files from a directory File[] fList = directory.listFiles(); for (File file : fList){ if (file.isFile()){ System.out.println(file.getAbsolutePath()); } else if (file.isDirectory()){ listFilesAndFilesSubDirectories(file.getAbsolutePath()); } } }` Now loop through your list of files reading each one. Now iterate the list containing the words, check with each word. If you find the word, add the file name in another list. See to that you iterate the file in the outer loop and the word inside the file loop.

Categories : Java

PHP FILES Recursive backup of directories, deleting main directory
As shown from your function-output, the directories are not empty. I suppose that the data is of low value and just needs to be backed up. I assume you are running Linux from your choice of a slash rather than a backslash. Naturally directories incur links or inodes, with metadata, which in linux can be checked via df -hi The Inode-Ids of files can be shown via the -i flag of ls ls -i filename ls -iltr ls -ltri `echo $HOME` Inodes take up space, and introduce overhead in file-system operations. So much to the motivation to remove the directories. PHP's rmdir function to remove directories requires that The directory must be empty, and the relevant permissions must permit this. It is also non-recursive. Approach 1: flatten filenames and move the files to a backup directory, t

Categories : PHP

Unix script to recursively search a directory and sub directories to grep and print content between 2 patterns in file
This might work for you: find . -type f -exec awk 'BEGING {print FILENAME ":"} /Pattern1/ { p=1 ; next } /Pattern2/ {p=0} p==1 {print $0} END {print ""}' {} ; Note, this prints the FILENAME, even if Pattern1 was not found!

Categories : Unix

How to get current user's default movie directory and other default directories?
If you just want to get access to common directories like Documents, Desktop, Movies, etc., -[NSFileManager URLsForDirectory:inDomains:] is the API you're looking for. You'll want to use the NSUserDomainMask for the domains parameter and one of the NSSearchPathDirectory constants (like NSMoviesDirectory) for the directory parameter. If you're actually trying to get the list of folders the current user has in the "Favorites" section of their Finder sidebar (users can customize this list), this Stack Overflow question may have some answers for you.

Categories : Osx

Powershell script for comparing two directories and excluding certain files
If you simply want to know what are the differences between the two, the following script is what you might want: $T = Get-ChildItem T: -Recurse $V = Get-ChildItem V: -Recurse Compare-Object $T $V or in its compact form: compare (ls T: -Recurse) (ls V: -Recurse) Please note that it will simply compare every files found under T: and V: You can narrow your comparison by some filtering in Get-ChildItem cmdlet. EDIT update from comment, the following is the script that will list only unique value, stripping filename from starting character # , using TrimStart method of [String] Get-ChildItem -Recurse -Path T:,V: | %{ $_.Name.TrimStart('#') } | Sort-Object -Unique

Categories : Powershell

script to traverse through directories and subdirectories to list files
if [ -d "$f" ] ^ There needs to be a space between if and [. If you don't have a space, bash thinks you're trying to execute a command named if[. files="/data/*" for f in $files Also know that this won't work. To store a wildcard expansion in a variable like that you need to use an array. The syntax is a bit hairier... files=(/data/*) for f in "${files[@]}" Or you could write the wildcard inline the way you do with the inner loop. That would work fine. for f in "$mydir"/* For what it's worth, you could use find to recurse through all files and sub-directories recursively. find /data/ -type f -print0 | while read -d $'' file; do echo "Processing $file" done -type f matches files only. -print0 combined with -d $'' is a way to be extra careful with file names containin

Categories : Linux

Edit certain files in multiple directories using a shell script
Can you use find to match the user files ? e.g. find ./ -maxdepth 1 -name "user*" -exec script_that_does_text_replace.sh {} ; where script_that_does_text_replace.sh is the code you wrote above.

Categories : Bash

Get the current directory name via php script in another directory
I am not 100% sure of your questions, but it sounds like you are looking for the URL/Directory of the page you are currently on, not the directory of the header? What about: $_SERVER['PHP_SELF']; $_SERVER['REQUEST_URI']; $_SERVER['SCRIPT_NAME']; $_SERVER['SCRIPT_FILENAME']; $_SERVER['DOCUMENT_ROOT']; Those all give info about the current file open by the server based on the HTTP request it received.

Categories : PHP

PHP script to move a directory from one Linux server to another?
there are many ways to do this but the easiest seems to be to send your cmd with php's exec or passthru function. http://php.net/manual/en/function.exec.php http://www.php.net/manual/en/function.passthru.php Warning When allowing user-supplied data to be passed to this function, use escapeshellarg() or escapeshellcmd() to ensure that users cannot trick the system into executing arbitrary commands.

Categories : PHP

batch script to recursively loop sub-directories and find missing files in 2 folders
try this, for explanation see comments in the code: @ECHO OFF &SETLOCAL SET "folder1=this" SET "folder2=that" REM delete variables FOR /f "delims==" %%a IN ('set "$"') DO SET "%%a=" REM scanning folder1 FOR /r "%folder1%" %%a IN (*) DO SET "$%%~nxa=%%~a" REM compare with folder2 FOR /r "%folder2%" %%a IN (*) DO ( IF NOT DEFINED $%%~nxa ECHO missing IN %folder1%: %%a ) REM delete variables FOR /f "delims==" %%a IN ('set "$"') DO SET "%%a=" REM scanning folder2 FOR /r "%folder2%" %%a IN (*) DO SET "$%%~nxa=%%~a" REM compare with folder1 FOR /r "%folder1%" %%a IN (*) DO ( IF NOT DEFINED $%%~nxa ECHO missing IN %folder2%: %%a ) ECHO Done.

Categories : Batch File

How to create a bash script that will lower case all files in the current folder, then search/replace in all files?
Something like this should work: #!/bin/bash for file in *.html do lowercase=`echo $file | tr '[A-Z]' '[a-z]'` mv "$file" "$lowercase" for f in *.html do sed -i "s/$file/$lowercase/g" "$f" done done Change *.html to *.<extension> if you're working with something other than html files.

Categories : Bash

dump files from bash script in different directory from where python script ran it
You should change directory within the same command: cmd = "/path/to/executable/executable" outputdir = "/path/to/output/" subprocess.call("cd {} && {}".format(outputdir, cmd), shell=True)

Categories : Python

Bash script that move files from one directory with lots of files to a month folder
something like this? DEBUG=echo cd ${directory_with_files} for file in * ; do dest=$(stat -c %y "$file" | head -c 7) mkdir -p $dest ${DEBUG} mv -v "$file" $dest/$(echo "$file" | sed -e 's/.* (.*)/1/') done DISCLAIMER: test this in a safe copy of your files. I won't be responsible for any lost of data ;-)

Categories : Bash

Zip together all HTML files under current directory
What about this? find /your/path/ -type f -name "*.html" | xargs zip all_html_files.zip looks for all .html files under the directory /your/path (change it for yours). Then, pipes the result to xargs, which creates the zip file. Edit To junk the paths, add -j option: find /your/path/ -type f -name "*.html" | xargs zip -j all_html_files.zip

Categories : Linux

How do I make FindFirst look for files in the current directory?
The path '*.*' is relative to the root directory of the drive of the current working directory. You probably mean to pass GetCurrentDir + '*' to FindFirst. Or even better, TPath.Combine(GetCurrentDir, '*'). For example, this program demonstrates that you code works correctly provided that you pass an appropriate path to FindFirst. program FindFirstDemo; {$APPTYPE CONSOLE} uses SysUtils, IOUtils; var SR: TSearchRec; begin Writeln(GetCurrentDir); if FindFirst(TPath.Combine(GetCurrentDir, '*'),faAnyFile,SR)=0 then begin repeat Writeln(SR.Name); until FindNext(SR)<>0; FindClose(SR); end; Readln; end.

Categories : Delphi

Geting numbers of files in specific directory in Linux
scandir() example, requires dirent.h: struct dirent **namelist; int n=scandir(".", &namelist, 0, alphasort); // "." == current directory. if (n < 0) { perror("scandir"); exit(1); } printf("files found = %d ", n); free(namelist);

Categories : Linux

Optimal procedure to rename files in a linux directory
for file in index.html?*; do new=${file/?/_} # Substitute underscore for ? mv "$file" "$new" # Rename the file done See the Parameter Expansion section of the bash man page for information on the substitution syntax used.

Categories : Regex

How do you get the total size of all files of a certain type within a directory in linux?
Found it. ls -lR | grep .jpg | awk '{sum = sum + $5} END {print sum}' As I understand it: ls says list all the files in the directory. Adding in the -l flag says show me more details like owner, permissions, and file size. tacking on R to that flag says 'do this recursively'. Piping that to grep .jpg allows only the output from ls that contains '.jpg' to continue on to the next phase. Piping that output to awk '{sum = sum + $5} END {print sum}' says take each line and pull its fifth column element (file size in this case) and add that value to our variable sum. If we reach the end of the list, print that variables value.

Categories : Osx

Extract .tar File to Current Directory Automatically with Shell Script
You can try: -C, --directory DIR change to directory DIR and $(dirname "$x") for file directory for x in in /home/davidwright/attachments/*/*.tar do echo "extracting $x" tar -xvf "$x" -C "$(dirname "$x")" done

Categories : Bash

PHP loop through current directory files for image resize
There's two ways to solve this. You can use one of PHP's "Magic Constants," __PATH__ to show the path to that current file. However, ot all PHP installs have this built in. The function getcwd() returns the current directory you're looking at, which may not be where your file lives. You can try this: <?php chdir( dirname( __FILE__ ) ); echo getcwd(); ?> Once you pull the directory, you can feed it into your script as it is. Hope this helps.

Categories : PHP

Print out all files in current directory and subdirectories in Python
It's only a little more difficult using os.walk import os for dirpath, dirnames, filenames in os.walk('.'): for f in filenames: print os.path.join(dirpath, f) You can also express this as a generator expression for filename in (os.path.join(dp, f) for dp, dn, fn in os.walk('.') for f in fn): # do something with filename

Categories : Python

How to execute files added to .bashrc out of current directory?
Here is the solution: Composer showed an error that I was running the CGI version of php (stupid I know, I know). That was because I had an symlink in my bin dir to the cgi version. I changed the link it shows now to the CLI version of php. Now it works :)

Categories : Linux

Linux Bash Shell Script: How to "ls" a directory and check some output string?
To check for a directory: if [ ! -d '/var/aaaaaaa' ]; then echo 'no dir!' fi For file: if [ ! -f '/var/aaaaaaa' ]; then echo 'no file!' fi To check output: if ls '/var/aaaaaaa' 2>&1 | grep 'No such'; then echo 'no such'; fi To check when ls fails: if ! ls '/var/aaaaaaa' &> /dev/null; then echo 'failed' fi

Categories : Linux

Running a subprocess bash script from Python in the scripts current directory
Yep, Just before your loop programitically save the current working directory and change the current working directory to /some%s before the subprocess.call and then set it back to the original value when you are done. import os Orig = os.path.abspath('.') for i in range(1,100): os.chdir('/some%s' % i) subprocess.call(['./task.sh' % i, arg1]) os.chdir(Orig)

Categories : Python

Finding the Files with the Same Name and Sub-Directories But Different Contents in Two Main Directories
You want something like this: for i in /home/Rash/A/*.{cpp,h}; do j=${i//A/B/} if [ -e $j ]; then echo comparing $i and $j diff $i $j fi done

Categories : Linux

use an R script on all files in directory
This is untested, so it may be a bit off. I would make a new function, collect all the files and apply the function to each file. runForAll <- function(x) { emboss <- read.table(x,header=T) x <- table(emboss[,2],emboss[,3])/NROW(emboss[,3]) y <- as.vector(t(x)) nms <- expand.grid(colnames(x), rownames(x)) names(y) <- paste( nms[,2],nms[,1],sep="") return(t(y)) } my.files <- list.files(pattern = ".ss") outputs <- lapply(my.files, FUN = runForAll) library(plyr) one.header.output <- rbind.fill.matrix(outputs) write.table(one.header.output, file = "nontpsec.csv") You can also run this via R CMD.

Categories : R



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.