0

Below is the piece of code of my bash script, I want to get duplicate output of that script.

This is how my script runs #bash check_script -a used_memory

Output is: used_memory: 812632

Desired Output: used_memory: 812632 | used_memory: 812632

get_vals() {
     metrics=`command -h $hostname -p $port -a $pass info | grep -w $opt_var | cut -d ':' -f2 > ${filename}`
}

output() {
get_vals
if [ -s ${filename} ];
then
   val1=`cat ${filename}`
   echo "$opt_var: $val1"
   # rm $filename;
    exit $ST_OK;
else
     echo "Parameter not found"
     exit $ST_UK
fi
}

But when i used echo "$opt_var: $val1 | $opt_var: $val1" the output become: | used_memory: 812632

$opt_var is an argument.

ceving
  • 21,900
  • 13
  • 104
  • 178
blaCkninJa
  • 445
  • 2
  • 11
  • 22

1 Answers1

1

I had a similar problem when capturing results from cat with Windows-formatted text files. One way to circumvent this issue is to pipe your result to dos2unix, e.g.:

val1=`cat ${filename} | dos2unix`

Also, if you want to duplicate lines, you can use sed:

sed 's/^\(.*\)$/\1 | \1/'

Then pipe it to your echo command:

echo "$opt_var: $val1" | sed 's/^\(.*\)$/\1 | \1/'

The sed expression works like that:

  1. 's/<before>/<after>/' means that you want to substitute <before> with <after>
  2. on the <before> side: ^.*$ is a regular expression meaning you get the entire line, ^\(.*\)$ is basically the same regex but you get the entire line and you capture everything (capturing is performed inside the \(\) expression)
  3. on the <after> side: \1 | \1 means you write the 1st captured expression (\1), then the space character, then the pipe character, then the space character and then the 1st captured expression again

So it captures your entire line and duplicates it with a "|" separator in the middle.

vdavid
  • 2,434
  • 1
  • 14
  • 15
  • Getting error when i pipe it. `sed: -e expression #1, char 18: unterminated `s' command.` But when i install dos2unix and use `echo "$opt_var: $val1 | $opt_var: $val1"` it's working, although i am not using windows formatted text files. – blaCkninJa Aug 28 '18 at 11:50
  • @blaCkninJa Forgot the slash at the end. My bad. – vdavid Aug 28 '18 at 11:58
  • @blaCkninJa if you open your file with `vi -b "${filename}"` do you see a `^M` character before the end of each line? – vdavid Aug 28 '18 at 12:00
  • Yes, I found ^M end of line. What does it mean ? – blaCkninJa Aug 28 '18 at 12:06
  • @blaCkninJa It means it is Windows-formatted :) More info here: https://stackoverflow.com/questions/5843495/what-does-m-character-mean-in-vim#5843561 – vdavid Aug 28 '18 at 12:06
  • `tr -d '\r'` removes any [Carriage return](https://en.wikipedia.org/wiki/Carriage_return). – ceving Aug 28 '18 at 12:10
  • Thank you. How can i understand the `sed 's/^\(.*\)$/\1 | \1/'` ? Any guide to learn these regex. – blaCkninJa Aug 28 '18 at 12:10
  • @blaCkninJa I edited the answer to include more details. – vdavid Aug 28 '18 at 12:20