Arun
Arun

Reputation: 1763

Clarification of 'sed' usage

I just blindly followed a command from a tutorial to rename several folders at a time. Can anyone explain the meaning of "p;s" given as the argument to sed's -e option.

[root@LinuxD delsure]# ls
ar1  ar2  ar3  ar4  ar5  ar6  ar7
[root@LinuxD delsure]# find . -type d -name "ar*"|sed  -e "p;s/ar/AR/g"|xargs  -n2  mv
[root@LinuxD delsure]# ls
AR1  AR2  AR3  AR4  AR5  AR6  AR7

Upvotes: 0

Views: 84

Answers (3)

Ed Morton
Ed Morton

Reputation: 204721

One way in bash:

$ ls
ar6  ar7

$ find . -name 'ar*' | while IFS= read -r file; do echo mv "$file" "${file^^}"; done
mv ./ar6 ./AR6
mv ./ar7 ./AR7

get rid of the "echo" when you're happy with the output.

Upvotes: 0

Jonathan Wakely
Jonathan Wakely

Reputation: 171491

A sed script (the bit following the -e option) can contain multiple commands, separated by ;

The script in your example uses the p command to print the pattern space (i.e. the line just read from the input) followed by the s command to perform a substitution on the pattern space.

By default (unless the pattern space is cleared or the -n option is given to sed) after processing each line the current pattern spaceline is printed again, so the result of the substitution will be printed.

Another way to write the same thing would be:

sed  -e "p" -e "s/ar/AR/g"

This separates the commands into two scripts. Another way would be:

sed "p;s/ar/AR/g"

because if the only argument to sed is a script then the -e option is not needed

Upvotes: 1

jpm
jpm

Reputation: 3155

The argument to the -e option is a script consisting of two commands. The first is p, which prints the unadulterated input, the second is a standard, global substitution. So for input ar1, this should output

ar1
AR1

The other part of this trick is the -n2 option on xargs, which forces it to only use two arguments at a time (instead of as many as it can handle, which would produce very different results).

Upvotes: 1

Related Questions