Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

grep

bash

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.

like image 947
ParveenArora Avatar asked May 23 '12 17:05

ParveenArora


People also ask

How do I display grep results?

To Display Line Numbers with grep MatchesAppend the -n operator to any grep command to show the line numbers. We will search for Phoenix in the current directory, show two lines before and after the matches along with their line numbers.

How do I grep a specific line in Linux?

The grep command searches through the file, looking for matches to the pattern specified. To use it type grep , then the pattern we're searching for and finally the name of the file (or files) we're searching in. The output is the three lines in the file that contain the letters 'not'.


1 Answers

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.

like image 64
Dennis Williamson Avatar answered Nov 09 '22 18:11

Dennis Williamson