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
  • 13,486
  • 7
  • 36
  • 60
  • 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 `<` notation reads named file without invoking `cat`. The double quotes are very necessary around the variable in the `echo` command — see also [Capturing ulti-line output to a `bash` variable](http://stackoverflow.com/questions/613572/capturing-multiple-line-output-to-a-bash-variable/). Using the `read` command strips leading and trailing blanks. – Jonathan Leffler Aug 26 '13 at 01:23
  • @JonathanLeffler: Thanks for those hints. I wasn't aware that `cat` could be replaced by `<` in this situation. I generally always like to use double-quotes "just in case" as I tend to forget the rules about when they are or aren't necessary. – 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
  • 94,503
  • 21
  • 155
  • 181
  • 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