Returning line before after searching for pattern

I am reading a text file and want to return the line before after encountering search criteria.
The data looks like:
Test 1
X
1
1
1
1
Test 2
X
1
1
1
So I would like to search for X and return the line before.
I was able to return X but not the line before. Thanks!
readfile = readlines(filename); %filename is a .txt file
pat = " X "; %pattern
A = contains(readfile,pat);
display = readfile(A);

 採用された回答

Steven Lord
Steven Lord 2025 年 12 月 4 日

0 投票

A is a logical array with the same number of rows as the string array readfile. So if you remove/ignore the first element of A, it uses the logical value for row 2 to determine whether or not to select row 1, the logical value for row 3 to determine whether or not to select row 2, etc.
readfile = readlines("sampleText.txt")
readfile = 11×1 string array
"Test 1" "X" "1" "1" "1" "1" "Test 2" "X" "1" "1" "1"
pat = "X";
A = contains(readfile,pat)
A = 11×1 logical array
0 1 0 0 0 0 0 1 0 0 0
linesContainingX = readfile(A)
linesContainingX = 2×1 string array
"X" "X"
linesBeforeX = readfile(A(2:end))
linesBeforeX = 2×1 string array
"Test 1" "Test 2"
Note that if the first line of the file matches the pattern, starting your indexing using element 2 of A will skip that line in linesBeforeX; but then again, there isn't a "line before" the first line.
linesContainingTest = contains(readfile, "Test")
linesContainingTest = 11×1 logical array
1 0 0 0 0 0 1 0 0 0 0
linesBeforeContainingTest = readfile(linesContainingTest(2:end))
linesBeforeContainingTest = "1"

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeCharacters and Strings についてさらに検索

タグ

質問済み:

2025 年 12 月 4 日

回答済み:

2025 年 12 月 4 日

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by