如何在shell脚本上保留带有echo的前导空格?

hei*_*man 10 unix bash shell scripting

我有一个源文件,它是已合并在一起的多个文件的组合.我的脚本应该将它们分成原始的单个文件.

每当我遇到以"FILENM"开头的行时,这意味着它是下一个文件的开头.

文件中的所有细节线都是固定宽度; 所以,我现在遇到的问题是,当不应该截断以前导空格开头的行时会被截断.

如何增强此脚本以保留前导空格?

while read line         
do         
    lineType=`echo $line | cut -c1-6`
    if [ "$lineType" == "FILENM" ]; then
       fileName=`echo $line | cut -c7-`
    else
       echo "$line" >> $filePath/$fileName
    fi   
done <$filePath/sourcefile
Run Code Online (Sandbox Code Playgroud)

pet*_*ohn 21

删除前导空格是因为read将输入拆分为单词.要解决此问题,请将IFS变量设置为空字符串.像这样:

OLD_IFS="$IFS"
IFS=
while read line         
do
    ...
done <$filePath/sourcefile
IFS="$OLD_IFS"
Run Code Online (Sandbox Code Playgroud)


roo*_*ook 9

要保留IFS变量,您可以while按以下方式编写:

while IFS= read line
do
    . . .
done < file
Run Code Online (Sandbox Code Playgroud)

还要保留反斜杠使用read -r选项.