bash 如何在 shell 脚本上使用 echo 保留前导空格?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18055073/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 06:07:57  来源:igfitidea点击:

How do I preserve leading whitespaces with echo on a shell script?

bashshellunixscripting

提问by heisenbergman

I have a source file that is a combination of multiple files that have been merged together. My script is supposed to separate them into the original individual files.

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

Whenever I encounter a line that starts with "FILENM", that means that it's the start of the next file.

每当我遇到以“FILENM”开头的行时,就意味着它是下一个文件的开始。

All of the detail lines in the files are fixed width; so, I'm currently encountering a problem where a line that starts with leading whitespaces is truncated when it's not supposed to be truncated.

文件中的所有细节行都是固定宽度的;所以,我目前遇到了一个问题,其中以前导空格开头的行在不应该被截断时被截断。

How do I enhance this script to retain the leading whitespaces?

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

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

回答by petersohn

The leading spaces are removed because readsplits the input into words. To counter this, set the IFSvariable to empty string. Like this:

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

OLD_IFS="$IFS"
IFS=
while read line         
do
    ...
done <$filePath/sourcefile
IFS="$OLD_IFS"

回答by rook

To preserve IFSvariable you could write whilein the following way:

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

while IFS= read line
do
    . . .
done < file

Also to preserve backslashes use read -roption.

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