ParveenArora
ParveenArora

Reputation: 751

How to get output of grep in single line in shell script?

Here is a script which reads words from the file replaced.txt and displays the output each word in each line, But I want to display all the outputs in a single line.

#!/bin/sh
 echo
 echo "Enter the word to be translated"
 read a
IFS=" "     # Set the field separator
set $a      # Breaks the string into $1, $2, ...
for a    # a for loop by default loop through $1, $2, ...
    do
    {
    b= grep "$a" replaced.txt | cut -f 2 -d" " 
    }
    done 

Content of "replaced.txt" file is given below:

hllo HELLO
m AM
rshbh RISHABH
jn JAIN
hw HOW 
ws WAS 
ur YOUR
dy DAY

This question can't be appropriate to what I asked, I just need the help to put output of the script in a single line.

Upvotes: 5

Views: 36197

Answers (3)

NamertaArora
NamertaArora

Reputation: 373

You can also use

awk 'BEGIN { OFS=": "; ORS=" "; } NF >= 2 { print $2; }'

in a pipe after the cut.

Upvotes: 1

Dennis Williamson
Dennis Williamson

Reputation: 360733

Your entire script can be replaced by:

#!/bin/bash
echo
read -r -p "Enter the words to be translated: " a
echo $(printf "%s\n" $a | grep -Ff - replaced.txt | cut -f 2 -d ' ')

No need for a loop.

The echo with an unquoted argument removes embedded newlines and replaces each sequence of multiple spaces and/or tabs with one space.

Upvotes: 9

ruakh
ruakh

Reputation: 183612

One hackish-but-simple way to remove trailing newlines from the output of a command is to wrap it in printf %s "$(...) ". That is, you can change this:

b= grep "$a" replaced.txt | cut -f 2 -d" "

to this:

printf %s "$(grep "$a" replaced.txt | cut -f 2 -d" ") "

and add an echo command after the loop completes.

The $(...) notation sets up a "command substitution": the command grep "$a" replaced.txt | cut -f 2 -d" " is run in a subshell, and its output, minus any trailing newlines, is substituted into the argument-list. So, for example, if the command outputs DAY, then the above is equivalent to this:

printf %s "DAY "

(The printf %s ... notation is equivalent to echo -n ... — it outputs a string without adding a trailing newline — except that its behavior is more portably consistent, and it won't misbehave if the string you want to print happens to start with -n or -e or whatnot.)

Upvotes: 2

Related Questions