0

The variable v has \n and, hm, another type newline??

v='ab\n cd
 ef
'
printf '%b' "$v"
ab
 cd
 ef
printf '%s' "$v"
ab\n cd
 ef
printf '%s' "$v" | xxd
00000000: 6162 5c6e 2063 640a 2065 660a            ab\n cd. ef.
printf '%b' "$v" | xxd
00000000: 6162 0a20 6364 0a20 6566 0a              ab. cd. ef.

printf '%b' shows both newlines as the ASCII 10 character.

My function removes both type newlines but it uses different processes for each type.

remove() {
  local str="$1" chr='\\n\\t\\r' idx
  for (( idx=0; idx<${#chr}; idx+=$((${#chr} / 3)) )); do   
    str="${str//${chr:${idx}:3}}"
  done
  str=${str//[$'\n\t\r']}
  printf "${str}"
}

Is there a better way to handle both with a single process using only Bash?

I'm using GNU bash 4.4.19.

2

There aren't really two types of newlines; \n is just a character sequence until you pass it to printf '%b' or some other command such as echo -e that interprets it as a backslash escape sequence.

So you could use printf '%b' to convert any \n sequences to newlines, then remove all the newlines using parameter substitution and a bash C-string:

v='ab\n cd                     
 ef
'
printf -v w '%b' "$v"; printf '%s\n' "${w//$'\n'}"
ab cd ef
1
  • Using printf is simpler and avoids my duplicate process, thanks! – Buoy Mar 10 '18 at 18:32
0

You can simply use echo. Whithout -e and ", echo see \n as string and you can remove it using parameter substitution.

echo ${v//\\n}
4
  • This is a simpler approach and does remove both reps of newline but I've been stumped trying to put \\n in a variable such that it will still remove both reps of newline. Is there a way to make a variable of \\n work? – Buoy Mar 13 '18 at 13:36
  • Not sure I understand well. If you have var='test\\ntry', you can catch \\n like that : echo ${var//\\\\n} – ctac_ Mar 13 '18 at 15:27
  • I was mistaken. If I don't include ${v//\\n} in double quotes then echo replaces the actual newline with a space. If in double quotes then echo does not replace the actual newline in $v, only the newline symbol \n. I am looking for v='ab\n cd ef' with both representations of newline and rep='\\n' such that "${v//${rep}} will remove both representations of newline. – Buoy Mar 13 '18 at 19:11
  • Unfortunately this note feature eats the pasted in newline but the variable in the question above shows both reps of newline being entered into v. – Buoy Mar 13 '18 at 19:19

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.