Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: How to apply two string operations in one line?

Tags:

string

bash

I'd like to change the path and extension of a file in a variable at once e.g. do the following

for F in $( find /foo/bar -name "*.ext" ); do 
  Ftmp=${F%.ext}
  cp $F ${Ftmp//bar/b0r}.tmp 
done

without a temporary variable

Can two string operations be applied at once with bash only means?

like image 205
IljaBek Avatar asked Feb 01 '12 16:02

IljaBek


2 Answers

Use the Bash temporary variable

$_    Temporary variable; initialized to pathname of script or program
      being executed. Later, stores the last argument of previous command.
      Also stores name of matching MAIL file during mail checks.
for F in $( find /foo/bar -name "*.ext" )
do
  : ${F%.ext}
  cp $F ${_//bar/b0r}.tmp
done
like image 197
Zombo Avatar answered Sep 28 '22 21:09

Zombo


Well you can do it like without a temporary variable:

for F in $( find /foo/bar -name "*.ext" ); do 
     cp $F "$(sed 's/\.[^.]\+$/.tmp/;s/bar/b0r/' <<< $F)" 
done

But that's two new process. With simple variable expansion I think you need that temo variable.

Edit: thanks to @glenn jackman now it's one extra process.

Edit2: bash only with a single variable sort of:

for F in $( find /foo/bar -name "*.ext" ); do 
     F=${F/.ext/}
     cp ${F}.ext ${F/bar/b0r}.tmp
done
like image 22
Zsolt Botykai Avatar answered Sep 28 '22 19:09

Zsolt Botykai