Linux - Bash Redirect line to file

I wrote a simple script that reads the contents of a file and increments the aa number inside this file, then I keep this change using awk when I try ro redirecting a new String using '>' the whole line is redirected to one line and not like the original. which consists of 4 lines.

#!/bin/bash -x # This script is for Incrementing build numbers path=/home/RND/abrodov file=tst.txt tst=`cat $path/$file` printf "this is the content of the file before incrementing: \n $tst" newexpr=`awk '/^Build Number/{$4=$4+1;}1' /home/RND/abrodov/tst.txt` printf "\n the new content \n $newexpr" echo $newexpr > $path/$file 

This is the source file before running the script:

 Major Release Number = 4 Minor Release Number = 1 Service Pack Release Number = 2 Build Number = 22 

This content after I used the script:

 Major Release Number = 4 Minor Release Number = 1 Service Pack Release Number = 2 Build Number = 23 

I am trying to figure out how I can redirect text in the original format, which consists of 4 lines.

+7
linux bash shell awk sed
source share
1 answer

You need to wrap the variables in double quotes:

 echo "$newexpr" > "$path/$file" 

In this case, the quotes around $path/$file not really needed, but they do not harm.

More generally, you should also use $( ) , not backlinks:

 newexpr=$(awk '/^Build Number/{$4=$4+1;}1' "$path/$file") 

If you want to achieve the effect of changing the file "in place", you do not need to use a variable. You can use the temporary file as follows:

 awk '/^Build Number/{$4=$4+1;}1' "$path/$file" > /tmp/file && mv /tmp/file "$path/$file" 

The importance of using quotes

Double quotes keep the original data format. See This simple example that uses set -x to activate debug mode. Commands executed by the shell are displayed in lines starting with + . In fact, I see that you are already using #!/bin/bash -x . set -x does the same as. :

 $ s="1 > 2" $ set -x $ echo $s + echo 1 2 1 2 $ echo "$s" + echo '1 2' 1 2 

The original line contains a new line, but when you echo without quotes, it is interpreted as two arguments echo instead of a single argument that contains a new line. This is called field splitting. You can learn more about the importance of using double quotes by reading this wiki article .

+14
source share

All Articles