AWK can search and replace text as well, so there is no need to use grep
or sed
. The code bellow extracts substring from second column (webN
), increments N
, and substitutes second field with webN+1
$ cat testInput.txt
project web0
other
project web1
$ awk '/web/{ num=substr($2,4)+1;$2="web"num };1' testInput.txt
project web1
other
project web2
This will print edited file on screen. You can save that to another file like so awk [rest of code here] > fileName.txt
and replace original with new using mv fileName.txt oldFile.txt
Assuming that file.txt
contains lines of text that are divided into three columns with commas and that there are no additional commas anywhere, so each line has exactly two of them:
replacement="my string"
sed "s/,.*,/,$replacement,/" file.txt
Output:
SveUJW24ibppfePgYeYHz7fC0,my string,yL6mCP0Do28k4EoTZUfKfqNYiIhGxxkA
xyRG8Da6kY35xeIT492Lul7xu,my string,ne6RIM2TeMQAax1GgzL7FeDrnQyHPH1i
sxTf13KlAnjtXodJouQ9V6m5b,my string,GUnApYwwDCZxWGZtzKzTU6sJRgHlUUfQ
7cjW5DZlXw1LYzVugbVyqfxRX,my string,XttE1In9eZQ8puJVUriuNvx2AJAxviGf
XiLE8r9AMqy5YZQ9BbIS6m559,my string,DssiszVBa05pbVDSOXNRaFXRxw0eZKHf
Sygrl5287BViOn0uQ9uCYipB1,my string,sD2O46sbh1yVIluoyn6Zm2OKXYe05vV9
Qi6DxJ96M0hxNe4cgux3iJ1aS,my string,wk2eF3f9xk5HowLzDIL3hCCNSmx8Uwi8
ZIX7qp5IIPekA0kzBdFR4IUQZ,my string,99ilfJWoJEBsKOfYI3buFfher07OCz6Y
This will process all lines at once and replace the middle column with the same value each time. The changed content will be printed to the terminal by default, if you want to modify file.txt
in place instead, write sed -i
instead of plain sed
.
If you need to update the replacement variable for each line anyhow (here a new random string for each line), you can loop over the lines like this:
while read line ; do
replacement="random number $RANDOM"
sed "s/,.*,/,$replacement,/" <<< "$line"
done < file.txt
Example output:
SveUJW24ibppfePgYeYHz7fC0,random number 27584,yL6mCP0Do28k4EoTZUfKfqNYiIhGxxkA
xyRG8Da6kY35xeIT492Lul7xu,random number 2959,ne6RIM2TeMQAax1GgzL7FeDrnQyHPH1i
sxTf13KlAnjtXodJouQ9V6m5b,random number 5463,GUnApYwwDCZxWGZtzKzTU6sJRgHlUUfQ
7cjW5DZlXw1LYzVugbVyqfxRX,random number 12889,XttE1In9eZQ8puJVUriuNvx2AJAxviGf
XiLE8r9AMqy5YZQ9BbIS6m559,random number 3754,DssiszVBa05pbVDSOXNRaFXRxw0eZKHf
Sygrl5287BViOn0uQ9uCYipB1,random number 25375,sD2O46sbh1yVIluoyn6Zm2OKXYe05vV9
Qi6DxJ96M0hxNe4cgux3iJ1aS,random number 5284,wk2eF3f9xk5HowLzDIL3hCCNSmx8Uwi8
It's probably the easiest way to put this code snippet into a script file and then you ran redirect its output to a separate new file (not the original file from which you read!) like this:
bash my-replacement-script.sh > new-file.txt
Best Answer
Another
perl
way:The key here is the
/e
regexp option allowing us to use aperl
command result as a substitution string.