1

嗨,我有一个程序,如果用户输入文件名,我会从文件中读取,否则我会提示他们输入。

目前我正在做:

    input=$(cat)
    echo $input>stdinput.txt
    file=stdinput.txt

问题在于它不读取输入中的换行符,例如,如果我输入

s,5,8
kyle,5,34,2 
j,2

输出

s,5,8 k,5,34,2 j,2

要存储在文件中的预期输出是

s,5,8
kyle,5,34,2 
j,2

我需要知道如何在阅读时包含换行符。?

4

4 回答 4

4

echo将抑制换行符。您不需要附加$input变量,因为您可以直接将cat的输出重定向到文件:

file=stdinput.txt
cat > "$file"

此外,$filecat. 改变了这一点。


如果您在两个文件中都需要用户输入,$input那么tee就足够了。如果将cat(用户输入)的输出通过管道传输tee到输入,则将同时写入文件和$input

file=stdinput.txt
input=$(cat | tee "$file")
于 2013-11-01T22:32:24.673 回答
1

尝试在回显变量时引用它:

input=$(cat)
echo "$input">stdinput.txt
file=stdinput.txt

例子:

$ input=$(cat)
s,5,8
kyle,5,34,2 
j,2
$ echo "$input">stdinput.txt
$ cat stdinput.txt 
s,5,8
kyle,5,34,2 
j,2
$ 

虽然确实,不引用变量会导致您描述的情况

$ echo $input>stdinput.txt
$ cat stdinput.txt 
s,5,8 kyle,5,34,2 j,2
$ 
于 2013-11-01T22:40:49.170 回答
0

您可以使用这样的语法:

#!/bin/sh

cat > new_file << EOF
This will be line one
This will be line two
This will be line three
   This will be line four indented
Notice the absence of spaces on the next line
EOF

这里cat读取文本,直到遇到分隔符(EOF在我们的例子中)。分隔符字符串可以是任何东西。

于 2013-11-01T22:40:37.140 回答
0

会有printf帮助吗?

printf "$input">stdinput.txt
于 2013-11-01T22:45:39.060 回答