user3738064
user3738064

Reputation: 11

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.

Upvotes: 0

Views: 2004

Answers (4)

fedorqui
fedorqui

Reputation: 289505

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.

Upvotes: 6

Avinash Raj
Avinash Raj

Reputation: 174696

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.

Upvotes: 3

Kent
Kent

Reputation: 195039

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

Upvotes: 2

jaypal singh
jaypal singh

Reputation: 77085

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.

Upvotes: 2

Related Questions