0

I want to do something with user input to use in grep. Like, instead of

uin="first\nsecond\n"
printf $uin | grep d

which outputs second, I want to have the user input it, like

read uin

where the user could input "first\nsecond\n". Then the variable could be used in the grep line like above. Or if the user could input actual returns after entering first and second, that would be filled in as \n that would work also. This is meant to be run from the cli. Thanks.

2 Answers2

1

You could do:

echo>&2 "Please enter a multiline string, Ctrl-D, twice if not on an empty line to end:"
input=$(cat)
printf 'You entered: <%s>\n'

Note that $(...) strips all trailing newline characters, so that can't be used to input text that ends in newline characters.

To read exactly two lines, just call read twice:

IFS= read -r first
IFS= read -r second
printf 'You entered: <%s\n%s>\n' "$first" "$second"

To input one line and have the \n, \a, \x45, \0123¹... sequences expanded in it:

IFS= read -r line
expanded_line=$(printf %b "$line")
printf 'You entered: <%s>\n' "$expanded_line"

Or with bash/zsh or recent versions of ksh93u+m, avoiding the stripping of trailing newline characters:

IFS= read -r line
printf -v expanded_line %b "$line"
printf 'You entered: <%s>\n' "$expanded_line"

In any case


¹ Beware that's the echo style of expansion where octal sequences need a leading 0 (\0ooo), not the usual \ooo one as in the C language and as also recognised in the format argument of printf.

0

A one-liner bash script of grep d suffices. It will read stdin until user enters final line of ctrl-D.

Or put cat into a script:

#! /usr/bin/env bash

PATTERN=${1:-d} TMP=/tmp/user_input.txt

cat > ${TMP}

grep "${PATTERN}" ${TMP}

rm ${TMP}

Then you can sort, awk, or otherwise slice-n-dice the input repeatedly.

J_H
  • 866