需要使用Unix Shell脚本在每行末尾添加空间

时间:2019-03-28 07:20:35

标签: shell unix add space using

除了标题行,我需要在每行末尾添加空格。下面是我的文件示例:

13120000005000002100000000000000000000081D000
231200000000000    000     00XY018710V000000000                        
231200000000000    000     00XY018710V000000000
13120000012000007000000000000000000000081D000
231200000000000   000     00XY057119V000000000                        

所以第一行和第四行(从131200开始)是我的标题行...除了我的标题外,我希望每行末尾有7-8个空格。

请找到我当前正在使用的代码:

find_list=`find *.dat -type f`
Filename='*.dat'
filename='xyz'
for file in $find_list

do
 sed -i -e 's/\r$/         /' "$file"
  n=1
   loopcounterpre=""

newfile=$(echo "$filename" | sed -e 's/\.[^.]*$//')".dat"

while read line
do
        if [[ $line != *[[:space:]]* ]]

        then
                rowdetail=$line

                loopcounter=$( echo "$rowdetail" | cut -b 1-6) 
        if [[ "$loopcounterpre" == "$loopcounter" ]]
        then 
         loopcounterpre=$loopcounter
         #Increases the counter for  in the order of 001,002 and so on until the Pay entity is changed
         n=$((n+1))
        #Resets the Counter to 1 when the pay entity changes
        else
         loopcounterpre=$loopcounter
         n=1
        fi
        printf -v m "%03d" $n
        llen=$(echo ${#rowdetail})

        rowdetailT=$(echo "$rowdetail" | cut -b 1-$((llen-3)))
                ip=$rowdetailT$m
                echo "$ip" >> $newfile

        else
                rowdetail=$line
        echo "$rowdetail" >> $newfile
        fi

done < $file

bye
EOF

done

2 个答案:

答案 0 :(得分:1)

可以用一行 GNU sed替换整个脚本:

sed -is '/^131200\|^1351000/!s/$/       /' $(find *.dat -type f)

答案 1 :(得分:0)

使用awk:

$ awk '{print $0 ($0~/^(131200|1351000)/?"":"        ")}' file

print当前记录$0,如果它以$0~/^(131200|1351000)/开头则打印"",否则:打印" "