Given this input:
# Lines starting with # stay the same
# Empty lines stay the same
# only lines with comments should change
ls # show all major directories
# and other things
cd # The cd command - change directory
# will allow the user to change between file directories
touch # The touch command, the make file command
# allows users to make files using the Linux CLI # example, cd ~
bar foo baz # foo foo foo
I need to keep lines beginning with #
and lines not containing any comments as is, but align all other comments on the same column.
Desired Output:
# Lines starting with # stay the same
# Empty lines stay the same
# Only lines with # in middle should change and be aligned
ls # show all major directories
# and other things
cd # The cd command - change directory
# will allow the user to change between file directories
touch # The touch command, the make file command
# allows users to make files using the Linux CLI # exmaple, cd ~
bar foo baz # foo foo foo
Here what I have so far:
# Building an array out of input
while IFS=$'\n' read -r; do
lines+=("$REPLY")
done
# Looping through array and selecting elemnts that need change
for i in "${lines[@]}"
do
if [[ ${i:0:1} == ';' || $i != *";"* ]];
then
echo "DOESNT CHANGE: #### $i"
else
echo "HAS TO CHANGE: #### $i"
array+=( "${i%%";"*}" );
array2+=("${i##";"}")
fi
done
# Trying to find the longest line to decide how much space I need to add for each element
max = ${array[0]}
for n in "${array[@]}" ; do
((${#n} > max)) && max=${#n}
echo "Length:" ${#n} ${n}
done
#Longest line
echo $max
# Loop for populating array
for j in "${!array2[@]}" ; do
echo "${array2[j]} " | sed -e "s/;/$(echo "-%20s ;") /g"
done
I feel like I'm doing too much. I think there should be an easier way to tackle this problem.
column
eliminates empty lines by default, and the-e
option is to prevent that. You could work around it by inserting the separator character in empty lines as well:sed $'s/#/\001#/;s/^\$/\001/' input-file | column -ts $'\001'
– muru May 14 '18 at 05:37