0

I have a txt file contains a count with text description:

12 CASH
10 Tree
7 Computer Desk

Ideally I'd like to end up with

| CASH | 12 |
| Tree | 10 |
| Computer Desk | 7 |

I tried this awk statement below, which kind of works, but then I lose anything after the first word of the description. I feel like I should be using sed, but I'm struggling to come up with a workable solution.

awk '{ print "|" $2 "|" $1 "|" }' temp.txt

Result:

| CASH | 12 |
| Tree | 10 |
| Computer | 7 |
Rob Adams
  • 33
  • 3

3 Answers3

3

Try this with GNU sed:

sed -E 's/([0-9]+)[[:blank:]]+(.*)/| \2 | \1 |/' file

-E (undocumented) or -r: enable extended regular expressions

[0-9]+: match one or more digits (range 0 to 9)

[[:blank:]]: a Posix character class and represents a space or a tab

Community
  • 1
  • 1
Cyrus
  • 69,405
  • 13
  • 65
  • 117
  • 1
    I'd suggest `[[:blank:]]` instead of `[\t ]` – glenn jackman Dec 02 '15 at 14:26
  • @glennjackman: Yes! Thank you for this hint. I've updated my answer. – Cyrus Dec 02 '15 at 14:27
  • I was doing the same, but I was blocked using `\d`, which can be written using `[[:digit:]]`. – Aif Dec 02 '15 at 14:28
  • That worked, but do you mind explaining it? I get sed is searching for a number with zero or more digits, but then I'm lost after the `\t*` – Rob Adams Dec 02 '15 at 14:28
  • `[[:blank:]]` is a [Posix character class](http://stackoverflow.com/questions/12275332/how-to-use-double-brackets-in-a-regular-expression/12276342#12276342) and represents a space or a tab. See: [The Stack Overflow Regular Expressions FAQ](http://stackoverflow.com/questions/22937618/reference-what-does-this-regex-mean/22944075#22944075) – Cyrus Dec 02 '15 at 14:32
  • 1
    @Rob, The regular expression finds some digits (saves in first capturing group), some whitespace, and then any other text (the description) is saved in second capturing group. The replacement puts the description before the number, as requested. – glenn jackman Dec 02 '15 at 14:33
2

Yes, easy with sed:

sed 's/\([^ ]*\) \(.*\)/| \2 | \1 |/'

Nonspace before the first space goes to \1, the rest of the line goes to \2.

| CASH | 12 |
| Tree | 10 |
| Computer Desk | 7 |
choroba
  • 200,498
  • 20
  • 180
  • 248
0

Posix version

sed 's/\([^[blank:]]\{1,}\)[[:blank:]]\{1,\}([^[blank:]].\{1,}\)/| \2 | \1 |/' YourFile
NeronLeVelu
  • 9,372
  • 1
  • 21
  • 41