Frage

In some code i found command like follows :

ls | grep Directory 1.txt

but above is not working for me
can any one suggest proper command?

War es hilfreich?

Lösung

The command you are looking for is find. It will traverse an arbitrarily complex directory structure and report back all files which match the criteria you specify.

find . -name 1.txt -exec dirname {} \;

This runs the dirname command on each matching file, which prints just the directory name.

If you only want to go one directory deep, GNU find has a -maxdepth option, or you can just use the shell's wildcard matching facilities.

dirname */1.txt

This assumes the file exists directly in a subdirectory of the current directory, and will only work if there is exactly one wildcard match (dirname only works on one file at a time) and the various workarounds are not a lot more elegant than just using find.

If, on the other hand, you know that 1.txt exists in the current directory, the command pwd will print out the directory name.

The command grep Directory 1.txt will open the file 1.txt in the current directory, and print out any lines matching the text Directory. It will simply ignore the standard input you are feeding it from the ls command, which is just as well, because ls does not print "Directory" anywhere useful. Also, parsing ls output is very complex, so you should probably avoid trying.

Andere Tipps

From the Ubuntu forums, you could use

dirname `find . -name someFile.txt`

Alternatively,

dirname /some/path/to/a/file.txt

Or you could strip off the last bit of the path grep returns

$ F='~/Documents/file.txt'
$ echo $(dirname "$F")
~/Documents
$ echo ${F%/*}
~/Documents

Given (just) an arbitrary relative pathname like 1.txt, it is impossible to get the directory name.

Why? Because there could be lots of 1.txt files in different directories! And (presumably) you'd have no way of knowing which was the right one.

If you have a way to disambiguate potential multiple answers, then you could use the find command to search for the file, and the apply dirname to the resulting pathname. Refer to the respective manual entries, etcetera. (But beware that find will typically search lots of directories, and that is liable to be *expensive".)

If you know that 1.txt is in the "current directory", then what you are actually asking for is the pathname of the current directory. You can get that using the pwd command.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top