kirkegaard
kirkegaard

Reputation: 1138

Extract first word in colon separated text file

How do i iterate through a file and print the first word only. The line is colon separated. example root:01:02:toor

the file contains several lines. And this is what i've done so far but it does'nt work.

  FILE=$1 
 k=1
   while read line; do
       echo $1 | awk -F ':' 
 ((k++))
 done < $FILE

I'm not good with bash-scripting at all. So this is probably very trivial for one of you..

edit: variable k is to count the lines.

Upvotes: 0

Views: 2920

Answers (4)

zedfoxus
zedfoxus

Reputation: 37049

awk -F: '{print $1}' FILENAME

That will print the first word when separated by colon. Is this what you are looking for?

To use a loop, you can do something like this:

$ cat test.txt
root:hello:1
user:bye:2

test.sh

#!/bin/bash

while IFS=':' read -r line || [[ -n $line ]]; do
    echo $line | awk -F: '{print $1}'
done < test.txt

Example of reading line by line in bash: Read a file line by line assigning the value to a variable

Result:

$ ./test.sh
root
user

Upvotes: 3

Eric Renouf
Eric Renouf

Reputation: 14490

You can get the first word without any external commands in bash like so:

printf '%s' "${line%%:*}"

which will access the variable named line and delete everything that matches the glob :* and do so greedily, so as close to the front (that's the %% instead of a single %).

Though with this solution you do need to do the loop yourself. If this is the only thing you want to do with the variable the cut solution is better so you don't have to do the file iteration yourself.

Upvotes: 1

DannyK
DannyK

Reputation: 1552

A solution using perl

%> perl -F: -ane 'print "$F[0]\n";'  [file(s)]

change the "\n" to " " if you don't want a new line printed.

Upvotes: 2

choroba
choroba

Reputation: 241828

Use cut:

cut -d: -f1 filename
  • -d specifies the delimiter
  • -f specifies the field(s) to keep

If you need to count the lines, just

count=$( wc -l < filename )
  • -l tells wc to count lines

Upvotes: 4

Related Questions