Skip to content
Advertisement

Delete newlines from all elements of a array in shell

I try to solve a problem in shell. Im trying to find a way to delete all newlines from each element of an array. I tried to do this with a for loop. The Strings look like this (always three numbers, separated with dots) “14.1.3n” and I need to get rid of the newline at the end. This is what i tried to do: As a single-liner

for i in ${backup_versions[*]}; do backup_versions[$i]=echo "$i" | tr 'n' ' ' ; done

Easier to read

for i in ${backup_versions[*]}; 
do 

 backup_versions[$i]=echo "$i" | tr 'n' ' ' 

done

I think I try to reassign the element with the wrong syntax, but I tried every kind of writing i which I found or knew myself. The deletion of the newline works just fine and just the reassigning is my Problem.

Advertisement

Answer

If the strings are always of that form and don’t contain any whitespace or wildcard characters, you can just use the shell’s word-splitting to remove extraneous whitespace characters from the values.

backup_versions=(${backup_versions[*]})

If you used mapfile to create the array, you can use the -t option to prevent it from including the newline in the value in the first place.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement