1

I want to get rid of \n from variable I found many answers for that which say "use tr -d" but tr -d not work for me

echo "$test" | od -c
0000000   4   4   2   5   2  \n
0000006

then I use tr -d

test2=$(echo $test | tr -d '\n')

but nothing change

echo "$test2" | od -c
0000000   4   4   2   5   2  \n
0000006
  • The \n seems to be a normal text element. Try with tr -d '\\n' which does not search for a new line but rather for the text \n. – Thomas Feb 5 '16 at 9:47
  • tr -d '\n' works fine. As user @user1700494 said, echo print arguments for stdout + newline. echo -n echo without newline. – kshji Feb 5 '16 at 16:30
2

Use of tr -d '\n' , removes \n (i.e. newline character) as expected. But you are verifying this with echo command. Echo command itself will put new line character @ end of input string and hence you are unable to see expected output.

Check variable with below set of commands.

test2=$(echo "$test" | tr -d '\n')
printf "%s" $test2 | od -c
echo -n $test2 | od -c

Script Output:

0000000   h   e   l   l   o
0000005
0000000   h   e   l   l   o
0000005

Note: echo -n : From echo man page : -n do not output the trailing newline printf : does not append \n at end

2

echo is appending \n by default. Use -n to omit

[6]root@lab7:~> echo 'lol' |od -c
0000000   l   o   l  \n
0000004
[6]root@lab7:~> echo -n 'lol' |od -c
0000000   l   o   l
0000003

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.