简体   繁体   中英

Using awk in a file that has forward slashes in it

I have a file containing lines similar too ...

/home/test/gp/fish/lib/fish.eye
/home/test/gp/fish/kerf/pl/teeth.eye

I want to take the last string at the end of each line and put it at the start of the line, for example ..

cp fish.eye /home/test/gp/fish/lib/fish.eye
cp teeth.eye /home/test/gp/fish/kerf/pl/teeth.eye

Any help greatly appreciated

Thanks.

Use this for example:

$ awk -F/ '{print "cp", $NF, $0}' your_file
cp fish.eye /home/test/gp/fish/lib/fish.eye
cp teeth.eye /home/test/gp/fish/kerf/pl/teeth.eye

It sets / as field separator, so that the filename is the last field. Then it is a matter of printing accordingly.

Or safer, to handle filenames with spaces and globbing chars, etc ( thanks Ed Morton !):

awk -F/ '{printf "cp \"%s\" \"%s\"\n", $NF, $0}' your_file

In bash you can loop through the lines and make use of basename :

while IFS= read -r line
do
    echo "cp" "$(basename "$line")" "$line"
    #printf "cp %s %s\n" "$(basename "$line")" "$line" <-- this also works
done < your_file

basename returns the strip and suffix from filenames, so that from a name like /path/like/this.sh you get this.sh .

And the one through GNU sed ,

$ sed -r 's/^.*\/(.*)$/cp \1 &/' file
cp fish.eye /home/test/gp/fish/lib/fish.eye
cp teeth.eye /home/test/gp/fish/kerf/pl/teeth.eye

Text after last / symbol are fetched and stored into a group. Again in the replacement part, "cp group wholeline" helps to give the above output.

Using bash parameter substitution :

while read -r line; do
    echo "cp ${line##*/} $line" 
done < file
cp fish.eye /home/test/gp/fish/lib/fish.eye
cp teeth.eye /home/test/gp/fish/kerf/pl/teeth.eye

From the link:

${parameter##word} 

The word is expanded to produce a pattern just as in filename expansion 
(see Filename Expansion). If the pattern matches the beginning of the expanded value 
of parameter, then the result of the expansion is the expanded value of parameter 
with the shortest matching pattern (the ‘#’ case) or the longest matching pattern 
(the ‘##’ case) deleted.

these three sed one-liners should work too, but awk would be more straightforward:

sed 's/.*/& &/;s#[^ ]*/#cp #' file

and

sed 'h;s#.*/#cp #;G;s/\n/ /' file

and

sed 's#.*/\(.*\)#cp \1 &#' file

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM