Linux
bash中的複雜文本對齊
鑑於此輸入:
# 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
我需要保持以開頭的
#
行和不包含任何註釋的行保持原樣,但在同一列上對齊所有其他註釋。期望的輸出:
# 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
這是我到目前為止所擁有的:
# 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
我覺得我做的太多了。我認為應該有一個更簡單的方法來解決這個問題。
如果您的所有命令和參數不包含
#
, 和一個其他字元(例如字節 1 給出的 ASCII 字元),您可以插入該其他字元作為額外的分隔符並用於column
對齊註釋(請參閱此答案)。所以,像:$ sed $'s/#/\001#/' input-file | column -ets $'\001' # 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
如果您
column
不支持-e
避免消除空行,則可以在空行中添加一些內容(例如,空格或上面使用的分隔符):$ sed $'s/#/\001#/;s/^$/\001/' input-file | column -ts $'\001' # 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