aless80
aless80

Reputation: 3332

Insert sed in a one liner to strip a string from the filename

This should be an easy question. Using the linux terminal I want to crop images in a folder using convert and change their name using sed. For example, The following one liner crops the images in a folder as i expect:

for file in Screenshot*.png; do convert -crop 1925x1060+10+1 $file newname_$file; done

However, I want to strip the "Screenshot-" string from the filename. With sed I could use sed -n 's/Screenshot-//p' :

echo "Screenshot-1.png" | sed -n 's/Screenshot\-//p'

But how can I insert sed in the for loop above?

For example, if I have a folder with these images:

Screenshot.png  Screenshot-1.png  Screenshot-2.png  do_not_crop.png 

I expect to see these files:

Screenshot.png  1.png  2.png  do_not_crop.png

Additional points for who can tell me how to convert Screenshot.png to 0.png

Edit: based on hek2mgl's answer, this script works:

for file in Screen*png; 
do convert -crop 1925x1060+10+1 $file 
    $(if [[ "$file" == "Screenshot.png" ]];
     then echo "0.png";
     else echo "${file#Screenshot-}";
     fi);
done

and outputs 0.png

Upvotes: 1

Views: 26

Answers (1)

hek2mgl
hek2mgl

Reputation: 157990

I would use bash's parameter expansion rather than sed.

Example:

for file in Screenshot.png  Screenshot-1.png  Screenshot-2.png  do_not_crop.png ; do
    echo "${file#Screenshot-}"
done

Output:

Screenshot.png
1.png
2.png
do_not_crop.png

Upvotes: 3

Related Questions