2

Hi I have a program where if the user inputs a filename I read form the file else I will prompt them for input.

Currently I am doing:

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

The problem with this is it doesn't read the newline characters in input, for example if I input

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

output

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

The intended output to be stored in a file is

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

I need to know how to include the newline character while reading.?

4 Answers 4

4

echo will suppress the newlines. You don't need the additional $input variable as you can directly redirect cat's output to the file:

file=stdinput.txt
cat > "$file"

Also it makes more sense for me to define $file before the cat. Have changed this.


If you need the user input in both the file and $input then tee would suffice. If you pipe the output of cat (user input) to tee the input will be written to both the file and $input:

file=stdinput.txt
input=$(cat | tee "$file")
Sign up to request clarification or add additional context in comments.

2 Comments

I tried but when I cat the file i.e. cat $file it doesn't show anything.
cat $file works for me (means content is in the file).. But with my previous solution $input was empty. Have changed this and use tee now
2

Try quoting the variable while echoing it:

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

Example:

$ 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
$ 

while indeed, not quoting the variable leads to the situation you describe

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

Comments

0

You may use such syntax:

#!/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

Here cat reads text until it encounters delimeter (EOF in our case). Delimeter string may be anything.

Comments

0

Would printf help?

printf "$input">stdinput.txt

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.