Dominic Maben
Dominic Maben

Reputation: 45

Get sed to read from terminal

I'm sorry if this seems like a silly question, but I'm a little new to this. I need write a script to get a string from the terminal and use sed to print it back to the terminal, with one word on each line. eg. 'This is input' should give me
This
is
input

I tried my hand at writing the script, but it doesn't seem to work.

#!/bin/sh
echo -n 'Enter the text:' 
read text
sed -i "/$text/s/ /\n/g"

I've saved it in a file called 1.sed, and run it with the command ./1.sed Can anyone tell me where I'm going wrong?

Upvotes: 0

Views: 223

Answers (2)

Jotne
Jotne

Reputation: 41460

Doing the same with awk

echo 'this is input' | awk 1 RS=" "
this
is
input

Another version

echo 'this is input' | awk 'gsub(/ /,"\n")'

Upvotes: 0

jkshah
jkshah

Reputation: 11713

Change your sed command to following:

echo 'this is input' | sed -r 's/(\w+)\s+/\1\n/g'

(\w+)\s+ - capture a word which is followed by one or more space in \1

Upvotes: 2

Related Questions