0

I have a file consC that is a line of spaces and *'s that looks like this:

                                          **** **     *          

How do I read into a string that keeps the location of *'s intact without losing the spaces and then get the index of the *'s

2 Answers2

2
echo '          **  **   *****    *     ' > consC.txt
consC="$(cat consC.txt)"
echo "$consC"

Edit: One of the comments mentions that the second line can be simplified:

consC=$(< consC.txt)
  • No need to use cat as < will do the job,
  • and double-quotes not needed when using $(...) construct in an assignment

Although double-quotes are definitely needed in line 3: echo.

Adrian Pronk
  • 12,856
  • 7
  • 35
  • 58
  • Or, in `bash`, you can avoid the `cat` command by using `consC=$(< consC.txt)`. The double quotes aren't necessary in the `$(...)` notation (either variant); and the ` – Jonathan Leffler Aug 26 '13 at 01:23
  • @JonathanLeffler: Thanks for those hints. I wasn't aware that `cat` could be replaced by ` – Adrian Pronk Aug 26 '13 at 01:52
  • I use double quotes quite a lot too — again, better safe than sorry. – Jonathan Leffler Aug 26 '13 at 01:54
  • however when I try to use the same string to return the first location of the * character I am having trouble. I tried the usual: echo `expr "$consC" "*"` but that gave me expr:syntax error. Is there an awk version of the command that I can use. I need the indices of the *'s in the consC string. – user2662478 Aug 26 '13 at 05:19
1

You can also set the input field separator:

while IFS= read line; do
    echo "$line"
done < input
perreal
  • 90,214
  • 20
  • 145
  • 172
  • For a general solution, you want `read -r`, as plain `read` will interpret e.g. backslashes, not read them literally. – tripleee Aug 26 '13 at 03:11