5

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.

1
  • Your script is incomplete. Where is the echo (or printf) statement? The curly braces are redundant with the do/done. You only need one or the other. Commented May 24, 2012 at 3:25

3 Answers 3

9

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.)

Comments

1

You can also use

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

in a pipe after the cut.

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.