Bash Fixed Width Fields
Fixed-width fields are columns that sit at fixed character positions in every line. Each field is found by counting characters, not by searching for a separator.
Extract one column with cut
The code column sits at characters 11 to 13 in each line. cut prints only those characters.
printf 'Anna 042
Ben 117
' > data.txt
cut -c11-13 data.txtSlice one field with parameter expansion
The name occupies the first 10 characters and the code the next 3. Expansion slices each field by position.
line='Anna 042'
name=${line:0:10}
name=${name%% *}
code=${line:10:3}
echo "$name: $code"Skip lines too short to slice
A line shorter than 13 characters has no code field. The length check skips it instead of printing an empty field.
printf 'Anna 042
Al
Ben 117
' > data.txt
while IFS= read -r line; do
if [ "${#line}" -lt 13 ]; then
echo "skipped short line"
else
echo "${line:10:3}"
fi
done < data.txtExample
cat > roster.txt <<'EOF'
Anna 042
Ben 117
Cleo 208
EOF
while IFS= read -r line; do
name=${line:0:10}
name=${name%% *}
code=${line:10:3}
echo "$name: $code"
done < roster.txtKey points
- Fixed width: every line uses the same character positions for the same field.
- cut -c: select characters by position, such as cut -c11-13 for columns 11 to 13.
- Parameter expansion: ${line:10:3} takes 3 characters starting at position 10.
- Padding: short values are padded with spaces so later fields stay aligned.
- Short lines: check ${#line} before slicing, since a short line has no later field.
- Trimming: strip padding spaces from a sliced name before printing it.
- Honest limit: one ragged line can shift every field after it, so validate lengths.
In this example, a roster file holds three fixed-width lines. The loop reads one line at a time. For each line, expansion takes the first 10 characters as the name and the next 3 as the code. Padding spaces are stripped from the name, then the name and code print together.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which cut option selects characters by position?